import {
  reqUpdateUser,
  reqUploadFile
} from '../../../../api/login'
import {
  setStorage
} from '../../../../utils/storage'
import {
  userBehavior
} from './behavior'
Page({
  behaviors: [userBehavior],
  // 页面的初始数据
  data: {
    isShowPopup: false, // 控制更新用户昵称的弹框显示与否
  },
  // 显示修改昵称弹框
  onUpdateNickName() {
    this.setData({
      isShowPopup: true
    })
  },

  // 弹框取消按钮
  cancelForm() {
    this.setData({
      isShowPopup: false,
    })
  },
  // 弹窗确认按钮
  confirmForm(event) {
    // 获取用户输入的最新的昵称
    const {
      nickname
    } = event.detail.value

    setStorage('userInfo', {
      ...this.data.userInfo,
      nickname
    })
    this.setData({
      'userInfo.nickname': nickname,
      isShowPopup: false
    })

    this.setUserInfo({
      headimgurl: this.data.userInfo.headimgurl,
      nickname: nickname
    })
  },
  // 更新头像
  async chooseAvatar(event) {
    const {
      avatarUrl
    } = event.detail
    const res = await reqUploadFile(avatarUrl, 'file')
    if (res.code === 200) {
      setStorage('userInfo', {
        ...this.data.userInfo,
        headimgurl: res.data
      })
      this.setData({
        'userInfo.headimgurl': res.data
      })
      this.setUserInfo({
        headimgurl: res.data,
        nickname: this.data.userInfo.nickname
      })
    }
  },
  // 保存个人信息
  async saveUpdateInfo() {
    const res = await reqUpdateUser({
      ...this.data.userInfo
    })
    if (res.code === 200) {
      wx.navigateBack({})
      wx.flowerTipToast({
        title: "信息更新成功",
        icon: 'success'
      })
    }
  },
})